package com.myexample.computerinternetdemo.view.impl.act;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.myexample.computerinternetdemo.R;
import com.myexample.computerinternetdemo.presenter.MainActPresenter;
import com.myexample.computerinternetdemo.view.IMainActView;

public class MainActivity extends AppCompatActivity implements IMainActView {
    private EditText editText;
    private Button btn_send, btn_connect;
    private TextView showText;
    private MainActPresenter presenter;
    private static final int START = 1;
    private static final int CONNECTED = 2;
    private static final int DISCONNECTED = 3;
    private static final int CLEAR = 4;
    private static final int RECEIVE=0;
    private String ip = null;
    private final Handler handler = new Handler(Looper.myLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {

            switch (msg.what) {
                case RECEIVE:
                    if(presenter.isConnected()){
                        String str=presenter.getTextFromServer();
                        presenter.setText(str);
                        presenter.close();
                    }
                    break;
                case START:
                    if (presenter.isConnected()) {
                        presenter.setWillSentText();
                        presenter.sendTextToServer();
                        presenter.clearEditText();

                        //handler.sendEmptyMessageAtTime(RECEIVE,200);
                    } else {
                        presenter.showToast("未连接");
                    }

                    break;
                case CONNECTED:
                    Log.i("test_1","ip: "+ip);
                    if(ip==null||ip.equals("null")) {
                        presenter.showToast("IP 未设置");
                    }else{
                        new Thread(() -> {
                            if (presenter != null && !presenter.isConnected()) {
                                presenter.newInstance();
                                presenter.connected(ip);
                            }
                        }).start();
                        presenter.showToast("连接成功");
                    }
                    break;
                case DISCONNECTED:
                    new Thread(() -> presenter.close()).start();
                    presenter.showToast("手动关闭连接");
                    break;
                case CLEAR:
                    presenter.clearShowText();
                    break;
            }
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.my_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == R.id.set_ip) {
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

            LayoutInflater inflater = getLayoutInflater();
            View view = inflater.inflate(R.layout.view_layout, new LinearLayout(this), false);

            dialogBuilder.setView(view);
            final View finalView = view;

            dialogBuilder.setPositiveButton("确认", (dialog, which) -> {

                RadioGroup group = finalView.findViewById(R.id.radio_group);
                if (group.getCheckedRadioButtonId() == R.id.ip_192_168_43_226) {
                    ip = "192.168.43.226";

                } else if (group.getCheckedRadioButtonId() == R.id.ip_192_168_50_64) {
                    ip = "192.168.50.64";
                } else if (group.getCheckedRadioButtonId() == R.id.ip_192_168_137_1) {
                    ip = "192.168.137.1";
                }else if(group.getCheckedRadioButtonId()==R.id.ip_192_168_0_107){
                    ip="192.168.0.107";
                }else if(group.getCheckedRadioButtonId()==R.id.ip_192_168_0_111){
                    ip="192.168.0.111";
                }
                presenter.showToast("IP为: " + ip);
            });

            dialogBuilder.create().show();
        } else if (itemId == R.id.clear_textView) {
            handler.sendEmptyMessage(CLEAR);
        }else if(itemId==R.id.help){
            AlertDialog.Builder builder=new AlertDialog.Builder(this);
            builder.setTitle("帮助信息");
            builder.setMessage("1、单击发送按钮，发送输入框内容\n" +
                    "2、长按发送按钮，接收服务器返回内容\n" +
                    "3、单击连接按钮，进行socket连接\n" +
                    "4、长按连接按钮，断开socket连接\n" +
                    "5、接收服务器内容后自动断开连接，需要单机连接按钮");
            builder.create().show();
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.et_inputText);
        btn_send = findViewById(R.id.btn_sendText);
        showText = findViewById(R.id.tv_showText);

        presenter = new MainActPresenter();
        presenter.setMainActView(this);
        btn_send.setOnClickListener(event -> {
                handler.sendEmptyMessage(START);
        });
        btn_send.setOnLongClickListener(event->{
            handler.sendEmptyMessage(RECEIVE);
            return true;});
        //建立连接
        btn_connect = findViewById(R.id.btn_connected);
        btn_connect.setOnClickListener(v -> {
            handler.sendEmptyMessage(CONNECTED);
        });
        btn_connect.setOnLongClickListener(v -> {
            handler.sendEmptyMessage(DISCONNECTED);
            return true;
        });


    }

    @Override
    public String getEditTextText() {
        return editText.getText().toString();
    }

    @Override
    public void setText(String text) {
        String newText = showText.getText().toString() + "\n" + "服务端回馈信息： " + text+"\n"+"--------------";
        showText.setText(newText);
    }

    @Override
    public void setSendText() {
        String newText = showText.getText().toString() + "\n" + "-----------\n" + "向服务器发送： " + getEditTextText();
        showText.setText(newText);

    }

    @Override
    public void clearEditText() {
        editText.setText("");
    }

    @Override
    public void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void clearShowText() {
        showText.setText("");
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}